package com.chinaoryx;

import java.util.Date;
import java.util.Map;


/**
 * Created by IntelliJ IDEA.
 * User: hyman.zhang
 * Date: 12-1-26
 * Time: 下午11:38
 * To change this template use File | Settings | File Templates.
 */
public class MyThread implements Runnable {


    private String taskId;
    private int internal = 1000 * 3;
    private String taskClassName = null;
    private Map<String, Object> parameterMap = null;
    private TaskInterface task = null;

    private boolean waitFlag = false;


    public synchronized void setWaitFlag(boolean waitFlag) {
        this.waitFlag = waitFlag;
        System.out.println("set waitFlag=" + this.waitFlag);
        System.out.println(this);
    }

    public MyThread(String taskId, int internal, String taskClassName, Map<String, Object> parameterMap) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        this.taskId = taskId;
        this.internal = internal;
        this.taskClassName = taskClassName;
        this.parameterMap = parameterMap;
        task = (TaskInterface) Class.forName(this.taskClassName).newInstance();
        
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {

            task.doTask(this.taskId, this.parameterMap);

            System.out.println("Thread(" + taskId + ") internal......");
            try {
                Thread.sleep(this.internal);
            } catch (InterruptedException e) {
                System.out.println("Thread(" + taskId + ")  Be Interrupted.");
                break;
            }

            try {
                System.out.println(this);
                if (this.waitFlag == true) {
                    synchronized (this) {
                        this.waitFlag = false;
                        this.wait();
                    }
                }

            } catch (InterruptedException e) {
                System.out.println("Thread(" + taskId + ")  Be Interrupted.");
                break;
            }
        }
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
